package com.cqwshzj.framework.manager.impl;/**
 * @Description:
 * @Auther: Huang Zhijin
 * @Version: 1.0.0
 * @Date: 2021/4/7 11:20
 */

import com.cqwshzj.framework.manager.ElasticJobManager;
import com.cqwshzj.util.ElasticJobUtil;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 *
 * 〈〉
 *
 * @author Huang Zhijin
 * @create 2021/4/7
 * @since 1.0.0
 */
@Component
public class ElasticJobManagerImpl implements ElasticJobManager {

	public static final Logger log = LoggerFactory.getLogger(ElasticJobManagerImpl.class);

	@Autowired
	private ZookeeperRegistryCenter registryCenter;

	@Override
	public void addSimpleJob(String jobName, SimpleJob simpleJob, String cron, int shardingTotalCount, String shardingItemParameters) {
		final JobScheduler simpleJobScheduler = createSpringJobScheduler(jobName, simpleJob, cron, shardingTotalCount, shardingItemParameters);
		simpleJobScheduler.init();
	}

	@Override
	public SpringJobScheduler createSpringJobScheduler(String jobName, SimpleJob simpleJob, String cron, int shardingTotalCount, String shardingItemParameters) {
		return ElasticJobUtil.createSpringJobScheduler(jobName,simpleJob,cron,shardingTotalCount,shardingItemParameters,registryCenter);
	}

	@Override
	public LiteJobConfiguration getLiteJobConfiguration(String jobName,
														Class<? extends SimpleJob> jobClass,
														String cron,
														int shardingTotalCount,
														String shardingItemParameters) {
		return ElasticJobUtil.getLiteJobConfiguration(jobName,jobClass,cron,shardingTotalCount,shardingItemParameters);
	}

	@Override
	public boolean removeZkNodeByJobName(String jobName) {
		Assert.hasText(jobName ,"缺少参数 jobName");
		if (!jobName.startsWith("/")) {
			jobName = "/"+jobName ;
		}
		try {
			registryCenter.remove( jobName );
			return true;
		}catch (Exception e){
			log.error(" remove znode failed . jobName=["+jobName+"] . exception: "+e.getMessage(),e);
			return false;
		}
	}
}
